#include "DialogTypeList.h"
#include "DefineCommon.h"
#include "EControllerQtTree.h"
#include "EItem.h"
#include "qtreewidget.h"
#include "ui_DialogTypeList.h"

DialogTypeList::DialogTypeList(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::DialogTypeList)
{
    ui->setupUi(this);
    QList<int> splitterSize;
    splitterSize<<1<<4;
    // ui->splitter->setStretchFactor(0, 1);
    // ui->splitter->setStretchFactor(0, 0);
    ui->splitter->setSizes(splitterSize);

    QObject::connect(ui->buttonOk, 
                     SIGNAL(clicked(bool)),
                     this,
                     SLOT(slotButtonOk(bool ))
                     );
    QObject::connect(ui->buttonCancel, 
                     SIGNAL(clicked(bool)),
                     this,
                     SLOT(slotButtonCancel(bool ))
                     );
    QObject::connect(ui->treeWidget, 
                     SIGNAL(currentItemChanged(QTreeWidgetItem*, QTreeWidgetItem*)),
                     this,
                     SLOT(slotCurrentItemChanged(QTreeWidgetItem*, QTreeWidgetItem*))
                     );

    // WidgetVariantMatrix* wPtr = new WidgetVariantMatrix;
    // QListWidgetItem* item = new QListWidgetItem();
    // ui->listWidget->addItem(item);
    // ui->listWidget->setItemWidget(item, wPtr);
    
    m_controllerTree = NewSmartPtr(EControllerQtTree)();
    m_controllerTree->setTreeWidget(ui->treeWidget);

    ui->treeWidget->expandAll();

    ui->buttonOk->setEnabled(false);
}

DialogTypeList::~DialogTypeList()
{
    delete ui;
}

// void DialogTypeList::addToList(const QString& str)
// {
    // ui->listWidget->addItem(str);
// }

QString DialogTypeList::getSelectedTypeName()
{
    return m_selectedTypeName;
}

QTreeWidget* DialogTypeList::getTreeWidget()
{
    return ui->treeWidget;
}

EControllerPtr DialogTypeList::getController()
{
    return m_controllerTree;
}

void DialogTypeList::slotButtonOk(bool value)
{
    QTreeWidgetItem* item = ui->treeWidget->currentItem();
    if(item != nullptr)
    {
        m_selectedTypeName = item->text(0);
    }
    
    this->accept();
}

void DialogTypeList::slotButtonCancel(bool value)
{
    m_selectedTypeName = "";
    this->m_controllerTree->setSelectedItem(nullptr);
    this->accept();
}

void DialogTypeList::slotCurrentItemChanged(QTreeWidgetItem* current, QTreeWidgetItem* previous)
{
    EItemPtr tempEItem = this->m_controllerTree->getEItemByTreeItemPtr(current);
    if(tempEItem != nullptr)
    {
        QString tempStr = tempEItem->getDescription().data();
        ui->textEdit->setText(tempStr);
        
        EString funName = tempEItem->getName() + "_Fun_factory";
        EItemMetaFunctionPtr fun = tempEItem->getOrCreatMeta()->getFunction(funName);
        if(fun != nullptr)
        {
            ui->buttonOk->setEnabled(true);
        }
        else 
        {
            ui->buttonOk->setEnabled(false);
        }

    }
    else 
    {
        ui->buttonOk->setEnabled(false);
    }
}
